<template>
	<view class="flex flex-col items-center p-3 h-full gap-5 pt-[20vh] fixed inset-0">
		<u-navbar
			back-text=""
			:is-back="true"
			title="登录"
			title-color="#000"
			class="z-50"
			:background="{ backgroundColor: '#f7f7f7' }"
			:border-bottom="false"
		>
		</u-navbar>

		<view class="w-[260rpx] aspect-square rounded-full">
			<u-image src="https://dsfw.oss-cn-shanghai.aliyuncs.com/baolian/202404181456908.png"></u-image>
		</view>

		<button
			class="bg-gray-900 text-white h-[80rpx] rounded-md w-2/3 flex items-center cu-btn"
			hover-class="bg-gray-600"
			open-type="getPhoneNumber"
			@getphonenumber="clickToLogIn"
			v-if="state.agrees"
		>
			<text class="cuIcon-weixin mr-1 text-lg text-white"></text>
			微信账号一键登录
		</button>
		<button
			class="bg-gray-900 text-white h-[80rpx] rounded-md w-2/3 flex items-center cu-btn"
			hover-class="bg-gray-600"
			@click="vk.alert('请先同意用户协议和隐私政策!!')"
			v-if="!state.agrees"
		>
			<text class="cuIcon-weixin mr-1 text-lg text-white"></text>
			微信账号一键登录
		</button>
		<view class="flex items-center gap-1 text-xs *:whitespace-nowrap" @click="state.agrees = !state.agrees">
			<view
				class="size-[26rpx] border border-solid rounded-full"
				:class="state.agrees ? ' bg-blue-600 border-blue-600' : ''"
			>
			</view>
			<text>登录/注册即代表您已同意 </text>
			<text class="font-bold text-blue-700" @click.stop="vk.navigateTo('/pages/my/service')">《用户服务协议》</text>
			<text>及</text>
			<text class="font-bold text-blue-700" @click.stop="vk.navigateTo('/pages/my/privacy')">《隐私政策》</text>
		</view>
	</view>
</template>
<script setup>
const state = ref({
	agrees: true,
});
const clickToLogIn = async (e) => {
	const {
		detail: { errMsg },
	} = e;
	if (errMsg === 'privacy permission is not authorized') {
		return vk.alert('拒绝用户隐私保护提示，将无法进行登录。');
	}
	if (errMsg === 'privacy permission is not authorized in gap') {
		return vk.alert('已拒绝用户隐私，请稍后再试。');
	}

	if (errMsg === 'getPhoneNumber:fail user deny') {
		return vk.alert('拒绝获取并验证手机号，将无法进行登录。');
	}

	vk.showLoading('登录中...');
	let loginCode = await vk.userCenter.getWeixinCode();

	const {
		detail: { encryptedData, iv, code },
	} = e;
	let obj = {
		loginCode,
		phoneCode: code,
	};

	const res = await api.wxLogin(obj);

	vk.setStorageSync('uni_id_token', res.data.access_token);
	// 更新用户信息
	await vk.myfn.updateUserInfo();
	vk.alert('登录成功!', () => {
		loginSuccess();
	});
};
const loginSuccess = async (params) => {
	if (vk.navigate.getOriginalPage()) {
		vk.navigate.originalTo();
		return false;
	}
	// 跳转到首页,或页面返回
	let pages = getCurrentPages();
	if (pages.length >= 2 && pages[pages.length - 2].route && pages[pages.length - 2].route.indexOf('login') == -1) {
		const currentPage = pages[pages.length - 2];
		vk.switchTab(`/${currentPage.route}`);
	} else {
		vk.navigateToHome();
	}
};
</script>

<style lang="scss" scoped>
::v-deep u-image view,
.u-image {
	@apply w-full h-full #{!important};
}
</style>
